//
//  DRFoodPairingVC.m
//  DoctorRen
//
//  Created by Lemon on 2018/11/19.
//

#import "DRFoodPairingVC.h"
#import "DRFoodPairingDataModel.h"
#import "DRFoodCell.h"
#import "DRFoodPairingHeaderView.h"
#import "DRFoodPairingFooterView.h"
#import <Masonry/Masonry.h>
#import "DRExtraMealVC.h"
#import "DRInviteFriendsView.h"
#import "DRFriendsFoodPairingVC.h"
#import "DRPopupView.h"

@interface DRFoodPairingVC ()<UITableViewDelegate, UITableViewDataSource ,DRFoodPairingFooterViewDelegate>
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *analyzeBtn;

@property (nonatomic, strong) DRFoodPairingModel *model;

//@property (nonatomic, strong) DREnergyTipModel *tipModel;

@property (nonatomic, assign) NSInteger type;

@property (nonatomic, strong) DRInviteFriendsView *inviteView;

@property (nonatomic, strong) DRFriendsFoodPairingVC *friendsVC;

@property (nonatomic, assign) BOOL popupViewIsShow;

@property (nonatomic, assign) NSInteger requestCount;

@end

@implementation DRFoodPairingVC{
}


-(DRInviteFriendsView *)inviteView{
    if (!_inviteView) {
        _inviteView = [[DRInviteFriendsView alloc] init];
//        [_inviteView setHidden:YES];
        [self.view addSubview:_inviteView];
        [_inviteView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.left.right.mas_equalTo(0);
        }];
        [_inviteView.inviteButton addTarget:self action:@selector(inviteFriends) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _inviteView;
}

-(DRFriendsFoodPairingVC *)friendsVC{
    if (!_friendsVC) {
        _friendsVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"DRFriendsFoodPairingVC"];
        [self addChildViewController:_friendsVC];
        [self.view addSubview:_friendsVC.view];
        [_friendsVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.analyzeBtn.superview.mas_bottom);
            make.left.right.mas_equalTo(0);
            make.bottom.mas_equalTo(self.inviteView.mas_top);
        }];
        WEAKSELF
        [_friendsVC showAlert:^(NSError * _Nonnull error) {
            STRONGSELF
            [strongSelf showAlerView:error.localizedDescription subTitle:error.code == 400 ?@"请正确填写资料" : @""];
        }];
    }
    return _friendsVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self loadData];
    [self.inviteView setHidden:YES];
    WEAKSELF
    self.inviteView.delFriendBlock = ^(NSString * _Nonnull userId) {
        STRONGSELF
        [strongSelf delFriend:userId];
    };
    _popupViewIsShow = NO;
    [SVProgressHUD showWithStatus:@"正在加载"];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self setKefuButtonHidden:NO];
    [self loadData];
    if (self.segmentControl.selectedSegmentIndex == 1) {
        [self getFriendList];
    }
}

- (IBAction)clickSegment:(UISegmentedControl *)sender {
    BOOL indexIsFrist = sender.selectedSegmentIndex == 0;
    if (indexIsFrist) {
        [self loadData];
    }else{
        [self getFriendList];
        [self.friendsVC reloadData];
    }
    [self.tableView setHidden:!indexIsFrist];
    [self.friendsVC.view setHidden:indexIsFrist];
    [self.inviteView setHidden:indexIsFrist];

}


- (NSInteger)type{
    NSInteger type = 1;
    return type;
}


-(void) loadData{
    [DRFoodPairingDataModel loadFoodPairingDataWithType:self.type andSuccess:^(DRFoodPairingModel * _Nonnull model) {
        [SVProgressHUD dismiss];
        self.model = model;
        [self.tableView reloadData]; 
        self.requestCount = 0;
    } andFail:^(NSError *error) {
        if (error.code == 400 || error.code == 300) {
            [SVProgressHUD dismiss];
            [self showAlerView:error.localizedDescription subTitle:error.code == 400 ?@"请正确填写资料" : @""];
            self.requestCount = 0;
        }else if (error.code == 500) {
            [SVProgressHUD dismiss];
            WEAKSELF
            if (![DRLoginDataModel isLogin]) {
                [SVProgressHUD showErrorWithStatus:@"智能配餐需要用户登录后才能查看"];
                return ;
            }
            [DRLoginDataModel setIsLogin:NO];
            [self presentAlertViewWithTitle:@"请重新登录" message:@"" confirmTitle:@"确定" handler:^{
                [weakSelf presentNeedLogin:NO];
            }];
            self.requestCount = 0;
        }else{
            if (self.requestCount <= 10) {
                self.requestCount += 1;
                [self loadData];
            }else{
                if ([error.localizedDescription isEqualToString:@"未能读取数据，因为它的格式不正确。"] || [error.localizedDescription containsString:@"The data couldn"]) {
                    [SVProgressHUD showErrorWithStatus:@"本次未能给您匹配出相应数据，请重新请求"];
                }else{
                    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                }
                self.requestCount = 0;
            }
        }
    }];
}

-(void) getFriendList{
    [DRFoodPairingDataModel getFriendListSuccess:^(NSArray<DRFriendModel *> * _Nonnull datas) {
        [self.inviteView setDatas:datas];
    } andFail:^(NSError *error) {
        
    }];
}

-(void) delFriend:(NSString *) userId{
    [DRFoodPairingDataModel delDietFirendWithId:userId andSuccess:^{
        [self getFriendList];
        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        [self.friendsVC reloadData];
    } andFail:^(NSError *error) {
        
    }];
}

-(void) showAlerView:(NSString *) title subTitle:(NSString *)subTitle{
    if (_popupViewIsShow) {
        return;
    }
    WEAKSELF
    DRPopupView *popupView = [[DRPopupView alloc] initWithTitle:title subTitle:subTitle];
    __weak typeof(popupView) weakPopupView = popupView;
    [popupView fristAction:^{
        STRONGSELF
        [strongSelf pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/tyerapy/profile?type=1&token=%@&isBack=1",[DRLoginDataModel getUserToken]]];
        [weakPopupView removeFromSuperview];
         strongSelf.popupViewIsShow = NO;
    } secondAction:^{
        STRONGSELF
        UITabBarController *tab = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        tab.selectedIndex = 0;
        [weakPopupView removeFromSuperview];
        strongSelf.popupViewIsShow = NO;
    }];
    popupView.frame = KEY_WINDOW.frame;
    [KEY_WINDOW addSubview:popupView];
    _popupViewIsShow = YES;
}


-(void) setBlackListWithId:(NSString *) foodId dietId:(NSString *) deitId indexPath:(NSIndexPath *) indexPath{
    [DRFoodPairingDataModel setBlackListWithFoodId:foodId andDietId:deitId andSuccess:^(DRFoodMode * _Nonnull model){
        [SVProgressHUD showSuccessWithStatus:@"食物已拉黑"];
        if (model == nil) {
            [self loadData];
        }else{
            [self replaceFoodModel:indexPath newFoodModel:model];
        }
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

-(void) gotoOptional:(NSString *) foodId meal:(NSString *) meal{
    NSString *url = [NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/treasureList?ctcp=%@&id=%@&ctype=1&type=5&token=%@&isBack=1",meal, foodId , [DRLoginDataModel getUserToken]];
     NSLog(@"%@",url);
    [self pushWebViewWithUrl:url];
}

-(void) changeFood:(NSString *) foodId indexPath:(NSIndexPath *) indexPath{
    [DRFoodPairingDataModel autoChangeFood:foodId andSuccess:^(DRFoodMode * _Nonnull model) {
        [self replaceFoodModel:indexPath newFoodModel:model];
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

-(void) replaceFoodModel:(NSIndexPath *)indexPath newFoodModel:(DRFoodMode *) newModel{
    switch (indexPath.section) {
        case 0:
        {self.model.breakfast[indexPath.row] = newModel;}
            break;
        case 1:
        {self.model.lunch[indexPath.row] = newModel;}
            break;
        case 2:
        {self.model.dinner[indexPath.row] = newModel;}
            break;
        default:
        {self.model.jia[indexPath.row] = newModel;}
            break;
    }
    [self.tableView reloadData];
}


-(void)inviteFriends{
    NSString *url = [NSString stringWithFormat:@"http://rsjkkj.com/dist/#/my/myfriend?addtype=1&token=%@&isBack=1",[DRLoginDataModel getUserToken]];
    [self pushWebViewWithUrl:url];
}

- (IBAction)clickAnalyzeBtn:(id)sender {
    NSString *url = [NSString stringWithFormat:@"http://rsjkkj.com/dist/#/tyerapy/dietReport?ctype=%d&token=%@&isBack=1",self.segmentControl.selectedSegmentIndex == 0 ? 1: 2,[DRLoginDataModel getUserToken]];
    [self pushWebViewWithUrl:url];
}

#pragma mark --DRFoodPairingFooterViewDelegate

-(void)didSelectedSetEatButton:(NSInteger)section{
    [DRFoodPairingDataModel existsRecord:[DRFoodPairingDataModel getMealTypeWithIndex:section] andSuccess:^(BOOL isOk) {
        if (isOk) {
            [self setEatFood:section];
        }else{
            [MMAlertViewConfig globalConfig].itemNormalColor = [UIColor darkTextColor];
            [MMAlertViewConfig globalConfig].itemHighlightColor = UIColorFromHex(0x888888);
            MMPopupItem *item1 = MMItemMake(@"否", MMItemTypeNormal, ^(NSInteger index) {});
            item1.highlight = YES;
            WEAKSELF
            MMPopupItem *item2 = MMItemMake(@"是", MMItemTypeNormal, ^(NSInteger index) {
                STRONGSELF
                [strongSelf setEatFood:section];
            });
            [self showAlert:@"是否替换已有记录" detail:@"" items:@[item1 ,item2]];
        }
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];

}

-(void) setEatFood:(NSInteger) section{
    [DRFoodPairingDataModel setEatFoodWithType:2 andMealType:section andSuccess:^(NSString * msg) {
        [SVProgressHUD showSuccessWithStatus:msg];
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.model == nil) {
        return 0;
    }
    switch (section) {
        case 0:
            return self.model.breakfast.count ;
            break;
        case 1:
            return self.model.lunch.count ;
            break;
        case 2:
            return self.model.dinner.count ;
            break;
        case 3:
            return self.model.jia.count ;
            break;
        default:
            return 0;
            break;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DRFoodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRFoodCell" forIndexPath:indexPath];
    DRFoodMode *foodModel;
    switch (indexPath.section) {
        case 0:
            foodModel = self.model.breakfast[indexPath.row];
            break;
        case 1:
            foodModel = self.model.lunch[indexPath.row];
            break;
        case 2:
            foodModel = self.model.dinner[indexPath.row];
            break;
        default:
            foodModel = self.model.jia[indexPath.row];
            break;
    }
    [cell setFoodData:foodModel];
    WEAKSELF
    
    MGSwipeButton *button1 = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"lahei"] backgroundColor:[UIColor whiteColor] padding:10 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
        STRONGSELF
        [strongSelf setBlackListWithId:foodModel._id dietId:foodModel.dietid indexPath:indexPath];
        return YES;
    }];
    button1.imageView.contentMode = UIViewContentModeScaleAspectFill;
    button1.backgroundColor = UIColorFromHex(0xF4F4F4);
    cell.rightButtons = @[button1];
    
    cell.reloadAction = ^{
        STRONGSELF
        [strongSelf changeFood:foodModel._id indexPath:indexPath];
    };
    
    cell.optionalAction = ^{
        STRONGSELF
        [strongSelf gotoOptional:foodModel._id meal:[DRFoodPairingDataModel getMealTypeWithIndex:indexPath.section]];
    };
    
    return  cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    DRFoodPairingHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"DRFoodPairingHeaderView"];
    if (!headerView) {
        headerView = [[DRFoodPairingHeaderView alloc] initWithReuseIdentifier:@"DRFoodPairingHeaderView"];
    }
    switch (section) {
        case 0:
            headerView.titleLB.text = @"早餐";
            self.model.zao ? headerView.contentLabel.text = self.model.zao : nil;
            break;
        case 1:
            headerView.titleLB.text = @"午餐";
            self.model.wu ? headerView.contentLabel.text = self.model.wu : nil;
            break;
        case 2:
            headerView.titleLB.text = @"晚餐";
            self.model.wan ? headerView.contentLabel.text = self.model.wan : nil;
            break;
        case 3:
            headerView.titleLB.text = @"加餐";
            self.model.jia1 ? headerView.contentLabel.text = self.model.jia1 : nil;
            break;
        default:
            break;
    }
    return headerView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    DRFoodPairingFooterView *fooderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"DRFoodPairingFooterView"];
    
    if (!fooderView) {
        fooderView = [[DRFoodPairingFooterView alloc] initWithReuseIdentifier:@"DRFoodPairingFooterView"];
    }
    fooderView.section = section;
    fooderView.delegate = self;
    [fooderView.addButton setHidden:YES];
    return fooderView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 105;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DRFoodMode *foodModel;
    switch (indexPath.section) {
        case 0:
            foodModel = self.model.breakfast[indexPath.row];
            break;
        case 1:
            foodModel = self.model.lunch[indexPath.row];
            break;
        case 2:
            foodModel = self.model.dinner[indexPath.row];
            break;
        default:
            foodModel = self.model.jia[indexPath.row];
            break;
    }
    [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/detail?cookbook_id=%@&token=%@&isBack=1",foodModel.dietid , [DRLoginDataModel getUserToken]]];
}





@end
